//
// Created by yyl on 2021/11/26.
//

#include "MatrixConvert.h"
/**
 * 使用透视投影的话，远处的顶点看起来比较小，而在正射投影中每个顶点距离观察者的距离都是一样的
 *
 * 正射投影主要用于二维渲染以及一些建筑或工程的应用
 * 正射投影时，每一个顶点坐标都会直接映射到裁剪空间中而不经过任何精细的透视划分
 * (它仍然有进行透视划分，只是w分量没有被操作(它保持为1)因此没有起作用)。
 * 因为正射投影没有使用透视
 *
 * 注意每个矩阵被运算的顺序是相反的(记住我们需要从右往左乘上每个矩阵)
 *  Vclip = Mprojection * Mview * Mmodel * Vlocal
 *
 * @param matrix
 * @param screenWidth
 * @param screenHeight
 * @return
 */


//变换矩阵
mat4
MatrixConvert::convert(TransformMatrix matrix, int screenWidth, int screenHeight) {
    //透视投影
    mat4 projection = mat4(1.0);
    //视图
    mat4 view = mat4(1.0);
    mat4 model = mat4(1.0);
    //定义一个投影矩阵。我们希望在场景中使用透视投影
    //45度角观察  距离0.1w-100.0w 的  四个轴xyzw中的W
    projection = perspective(radians(45.0f), (float) screenWidth / (float) screenHeight, 1.0f,
                             100.0f);
    //
    view = translate(view, vec3(matrix.translateX, matrix.translateY, -1.0f));

    model = scale(model, vec3(matrix.scaleX, matrix.scaleY, 1.0f));
    //下面是Z轴转degree度数
    model = rotate(model, radians((float) matrix.degree), vec3(0.0, 0.0, 1.0));
    return projection * view * model;
}

//LookAt  位置 目标和上向量
mat4
MatrixConvert::convertOrtho(TransformMatrix matrix) {

    //正射投影
    mat4 projection = ortho(-1.0f, 1.0f, -1.0f, 1.0f, 0.1f, 100.0f);
    // mat4 Projection =  frustum(-ratio, ratio, -1.0f, 1.0f, 4.0f, 100.0f);
    // View matrix
    //相机矩阵
    mat4 view = lookAt(
            vec3(0, 0, 1), // Camera is at (0,0,1), in World Space
            vec3(0, 0, 0), // and looks at the origin
            vec3(0, 1, 0)  // Head is up (set to 0,-1,0 to look upside-down)
    );
//    view=translate(view,vec3(0.0f,0.0f,matrix.translateX-50.0f));
    mat4 model = mat4(1.0);
    model = scale(model, vec3(matrix.scaleX, matrix.scaleY, 1.0f));

    //下面是Z轴转degree度数
    model = rotate(model, radians((float) matrix.degree), vec3(0.0, 0.0, 1.0));

    model = translate(model, vec3(matrix.translateX, matrix.translateY, 0.0f));

    return projection * view * model;
}
